#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

/* 
    该模块只负责代码编译 
*/

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;

    const int UMASK = 0;
    const int PERMISSION = 0644;

    enum{
        OPEN_ERROR = 1,
        REPLACE_ERROR,
    };

    class Compiler
    {
    public:
        Compiler() = default;
        ~Compiler() = default;

       // file -> file.cpp   file.exe   file.stderr 
        static bool Compile(const std::string file_name)
        {
            umask(UMASK);
            
            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(ERROR) << "内部错误：创建子进程失败\n";
                return false;
            }
            else if(pid == 0)
            {
                int _stderr = open(PathUtil::CompileError(file_name).c_str(), O_CREAT | O_WRONLY, PERMISSION);
                if(_stderr < 0)
                {
                    LOG(WARNING) << "没有形成Stderr文件\n";
                    exit(OPEN_ERROR);
                }
                dup2(_stderr, 2);       // 将stderr重定向到文件

                // 程序替换：g++ -o target src -std=c++11
                execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(),\
                    PathUtil::Src(file_name).c_str(), "-std=c++11", "-D", "COMPILER_ONLINE", nullptr);

                LOG(ERROR) << "启动编译器g++失败\n";            
                exit(REPLACE_ERROR);
            }
            else
            {
                waitpid(pid, nullptr, 0);
                if(FileUtil::IsFileExists(PathUtil::Exe(file_name)))
                {
                    LOG(INFO) << PathUtil::Src(file_name).c_str() << " 编译成功\n";
                    return true;
                }
                LOG(DEBUG) << PathUtil::Src(file_name).c_str() << "\n";
                LOG(ERROR) << "编译失败, 没有形成可执行程序" << "\n";
                return false;
            }
        }
    };   
} 